// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

function generateToken(userId) {
  const timestamp = Date.now()
  const randomStr = Math.random().toString(36).substring(2, 15)
  return `${userId}_${timestamp}_${randomStr}`
}

function generateCode() {
  return Math.floor(100000 + Math.random() * 900000).toString()
}

function generateRandomCode(length = 6) {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
  let result = ''
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return result
}

function validatePassword(password) {
  const passwordReg = /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{6,20}$/
  return passwordReg.test(password)
}

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const {
    action,
    data
  } = event

  switch (action) {
    case 'passwordLogin':
      return await passwordLogin(data, wxContext)
    case 'quickLogin':
      return await quickLogin(data, wxContext)
    case 'register':
      return await register(data, wxContext)
    case 'sendVerifyCode':
      return await sendVerifyCode(data, wxContext)
    case 'checkVerifyCode':
      return await checkVerifyCode(data, wxContext)
    default:
      return {
        success: false,
          message: '未知操作'
      }
  }
}

// 密码登录
async function passwordLogin(data, wxContext) {
  console.log('\n=== 云函数密码登录开始 ===');
  console.log('登录数据:', data);
  console.log('微信上下文:', {
    OPENID: wxContext.OPENID,
    APPID: wxContext.APPID
  });

  const {
    account,
    password
  } = data

  if (!account || !password) {
    console.log('❌ 账号或密码为空');
    return {
      success: false,
      message: '账号和密码不能为空'
    }
  }

  try {
    console.log('🔍 查询用户，账号:', account);
    // 查询用户
    const userQuery = await db.collection('users')
      .where(_.or([{
          username: account
        },
        {
          phone: account
        },
        {
          email: account
        }
      ]))
      .get()

    console.log('查询结果:', userQuery.data.length, '个用户');

    if (userQuery.data.length === 0) {
      console.log('❌ 用户不存在');
      return {
        success: false,
        message: '用户不存在'
      }
    }

    const user = userQuery.data[0]
    console.log('找到用户:', {
      id: user._id,
      username: user.username,
      phone: user.phone,
      hasPassword: !!user.password
    });

    // 明文比对密码
    if (user.password !== password) {
      console.log('❌ 密码错误');
      return {
        success: false,
        message: '密码错误'
      }
    }

    console.log('✅ 密码验证通过');

    // 检查用户状态
    if (user.status === 'disabled') {
      console.log('❌ 账号已被禁用');
      return {
        success: false,
        message: '账号已被禁用'
      }
    }

    // 生成token
    console.log('🔑 生成token...');
    const token = generateToken(user._id)
    console.log('Token生成成功:', token.substring(0, 10) + '...');

    // 保存token到数据库
    console.log('💾 保存token到数据库...');
    await db.collection('user_tokens').add({
      data: {
        userId: user._id,
        token: token,
        createTime: new Date(),
        expireTime: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000), // 7天过期 -> 3天
        openid: wxContext.OPENID
      }
    })

    // 更新用户最后登录时间
    console.log('⏰ 更新用户最后登录时间...');
    await db.collection('users').doc(user._id).update({
      data: {
        lastLoginTime: new Date(),
        openid: wxContext.OPENID
      }
    })

    // 删除密码字段
    delete user.password

    const result = {
      success: true,
      message: '登录成功',
      token: token,
      userInfo: {
        id: user._id,
        username: user.username,
        nickname: user.nickname || user.username || `用户${user.phone ? user.phone.slice(-4) : ''}`,
        name: user.nickname || user.username || `用户${user.phone ? user.phone.slice(-4) : ''}`,
        phone: user.phone,
        email: user.email,
        avatar: user.avatar || '',
        role: user.role || 'user',
        level: user.level || 1,
        permissions: user.permissions || [],
        hasDefaultPassword: user.hasDefaultPassword || false,
        status: user.status || 'active',
        createTime: user.createTime,
        lastLoginTime: user.lastLoginTime || new Date(),
        loginTime: new Date().toISOString(),
        points: user.points || 0 // 包含积分信息
      }
    };

    console.log('✅ 密码登录成功，返回结果:', {
      success: result.success,
      message: result.message,
      token: result.token.substring(0, 10) + '...',
      userId: result.userInfo.id
    });

    return result;
  } catch (error) {
    console.error('❌ 密码登录异常:', error);
    return {
      success: false,
      message: '登录失败'
    }
  }
}

// 快速登录
async function quickLogin(data, wxContext) {
  console.log('\n=== 云函数快速登录开始 ===');
  console.log('快速登录数据:', data);

  const {
    phone,
    verifyCode
  } = data

  if (!phone || !verifyCode) {
    console.log('❌ 手机号或验证码为空');
    console.log('❌ 接收到的数据:', {
      phone,
      verifyCode
    });
    return {
      success: false,
      message: '手机号和验证码不能为空'
    }
  }

  try {
    console.log('🔍 验证验证码...');
    // 验证验证码 - 注意参数名要匹配checkVerifyCode函数的期望
    // const codeResult = await checkVerifyCode({ phone, code: verifyCode, type: 'login' }, wxContext)
    // console.log('验证码验证结果:', codeResult);

    // if (!codeResult.success) {
    //   console.log('❌ 验证码验证失败');
    //   return codeResult
    // }

    if (verifyCode !== '123456') {
      return {
        success: false,
        message: '请联系管理员要验证码'
      }
    }

    console.log('✅ 验证码验证成功');

    // 查询用户
    console.log('🔍 查询用户，手机号:', phone);
    let userQuery = await db.collection('users')
      .where({
        phone: phone
      })
      .get()

    console.log('查询到用户数量:', userQuery.data.length);

    let user
    let isNewUser = false

    if (userQuery.data.length === 0) {
      // 新用户，自动注册
      const defaultPassword = phone.slice(-6) // 使用手机号后6位作为默认密码
      const avatars = ['avatar-1.png', 'avatar-2.png', 'avatar-3.png', 'avatar-4.png', 'avatar-5.png'];

      function shuffle(array) {
        return array.sort(() => Math.random() - 0.5);
      }

      const shuffled = shuffle(avatars);
      const avatar = `static/${shuffled[0]}`;

      const newUser = {
        username: phone,
        phone: phone,
        password: defaultPassword, // 明文存储默认密码
        nickname: `用户${phone.slice(-4)}`,
        avatar: avatar,
        email: '',
        role: 'user',
        level: '会员',
        permissions: [],
        status: 'active',
        createTime: new Date(),
        openid: wxContext.OPENID,
        hasDefaultPassword: true, // 标记使用默认密码
        points: 20 // 新用户赠送10积分
      }

      const addResult = await db.collection('users').add({
        data: newUser
      })

      user = {
        ...newUser,
        _id: addResult._id
      }
      isNewUser = true
    } else {
      user = userQuery.data[0]

      // 检查用户状态
      if (user.status === 'disabled') {
        return {
          success: false,
          message: '账号已被禁用'
        }
      }

      // 更新openid
      await db.collection('users').doc(user._id).update({
        data: {
          openid: wxContext.OPENID,
          lastLoginTime: new Date()
        }
      })
    }

    // 生成token
    const token = generateToken(user._id)

    // 保存token到数据库
    await db.collection('user_tokens').add({
      data: {
        userId: user._id,
        token: token,
        createTime: new Date(),
        expireTime: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000), // 7天过期 -> 3 天
        openid: wxContext.OPENID
      }
    })

    // 删除密码字段
    delete user.password

    return {
      success: true,
      message: isNewUser ? '注册并登录成功' : '登录成功',
      token: token,
      userInfo: {
        id: user._id,
        username: user.username,
        nickname: user.nickname,
        phone: user.phone,
        email: user.email,
        avatar: user.avatar,
        role: user.role,
        level: user.level,
        permissions: user.permissions,
        hasDefaultPassword: user.hasDefaultPassword || false,
        status: user.status,
        createTime: user.createTime,
        lastLoginTime: user.lastLoginTime,
        points: user.points || 0 // 包含积分信息
      }
    }
  } catch (error) {
    console.error('快速登录失败:', error)
    return {
      success: false,
      message: '登录失败'
    }
  }
}

// 注册
async function register(data, wxContext) {
  const {
    username,
    password,
    confirmPassword,
    phone,
    email,
    verifyCode
  } = data

  if (!username || !password || !confirmPassword || !phone || !verifyCode) {
    return {
      success: false,
      message: '请填写完整信息'
    }
  }

  // 验证密码
  if (password !== confirmPassword) {
    return {
      success: false,
      message: '两次输入的密码不一致'
    }
  }

  // 验证密码强度
  if (password.length < 6 || password.length > 20) {
    return {
      success: false,
      message: '密码长度应为6-20位'
    }
  }

  if (!validatePassword(password)) {
    return {
      success: false,
      message: '密码应包含字母和数字'
    }
  }

  try {
    // 验证验证码
    const codeResult = await checkVerifyCode({
      phone,
      verifyCode,
      type: 'register'
    }, wxContext)
    if (!codeResult.success) {
      return codeResult
    }

    // 检查用户名是否已存在
    const usernameCheck = await db.collection('users')
      .where({
        username: username
      })
      .get()

    if (usernameCheck.data.length > 0) {
      return {
        success: false,
        message: '用户名已存在'
      }
    }

    // 检查手机号是否已存在
    const phoneCheck = await db.collection('users')
      .where({
        phone: phone
      })
      .get()

    if (phoneCheck.data.length > 0) {
      return {
        success: false,
        message: '手机号已被注册'
      }
    }

    // 检查邮箱是否已存在（如果提供了邮箱）
    if (email) {
      const emailCheck = await db.collection('users')
        .where({
          email: email
        })
        .get()

      if (emailCheck.data.length > 0) {
        return {
          success: false,
          message: '邮箱已被注册'
        }
      }
    }

    const avatars = ['avatar-1.png', 'avatar-2.png', 'avatar-3.png', 'avatar-4.png', 'avatar-5.png'];

    function shuffle(array) {
      return array.sort(() => Math.random() - 0.5);
    }

    const shuffled = shuffle(avatars);
    const avatar = `static/${shuffled[0]}`;

    // 明文存储密码
    const newUser = {
      username: username,
      password: password,
      phone: phone,
      email: email || '',
      nickname: username,
      avatar: avatar,
      role: 'user',
      level: '会员',
      permissions: [],
      status: 'active',
      createTime: new Date(),
      openid: wxContext.OPENID,
      hasDefaultPassword: false,
      points: 20 // 新用户赠送20积分
    }

    const addResult = await db.collection('users').add({
      data: newUser
    })

    // 生成token
    const token = generateToken(addResult._id)

    // 保存token到数据库
    await db.collection('user_tokens').add({
      data: {
        userId: addResult._id,
        token: token,
        createTime: new Date(),
        expireTime: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000), // 7天过期 -> 3天过期
        openid: wxContext.OPENID
      }
    })

    return {
      success: true,
      message: '注册成功',
      token: token,
      userInfo: {
        id: addResult._id,
        username: newUser.username,
        nickname: newUser.nickname,
        phone: newUser.phone,
        email: newUser.email,
        avatar: newUser.avatar,
        role: newUser.role,
        level: newUser.level,
        permissions: newUser.permissions,
        hasDefaultPassword: false,
        status: newUser.status,
        createTime: newUser.createTime,
        points: newUser.points // 包含积分信息
      }
    }
  } catch (error) {
    console.error('注册失败:', error)
    return {
      success: false,
      message: '注册失败'
    }
  }
}

// 发送验证码
async function sendVerifyCode(data, wxContext) {
  const {
    phone,
    type
  } = data

  if (!phone) {
    return {
      success: false,
      message: '手机号不能为空'
    }
  }

  if (!['login', 'register'].includes(type)) {
    return {
      success: false,
      message: '验证码类型不支持'
    }
  }

  try {
    // 检查是否已发送过验证码
    const existingCode = await db.collection('verify_codes')
      .where({
        phone: phone,
        type: type,
        expireTime: _.gte(new Date())
      })
      .get()

    if (existingCode.data.length > 0) {
      return {
        success: false,
        message: '验证码已发送，请稍后再试'
      }
    }

    const code = generateCode()
    const expireTime = new Date(Date.now() + 5 * 60 * 1000) // 5分钟过期

    await db.collection('verify_codes').add({
      data: {
        phone: phone,
        code: code,
        type: type,
        expireTime: expireTime,
        used: false,
        createTime: new Date()
      }
    })

    return {
      success: true,
      message: '验证码已发送'
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    return {
      success: false,
      message: '发送验证码失败'
    }
  }
}

// 验证验证码
async function checkVerifyCode(data, wxContext) {
  console.log('\n=== 云函数验证验证码开始 ===');
  console.log('验证码验证数据:', data);

  const {
    phone,
    code,
    type
  } = data

  if (!phone || !code) {
    console.log('❌ 手机号或验证码为空');
    return {
      success: false,
      message: '手机号和验证码不能为空'
    }
  }

  if (!['login', 'register'].includes(type)) {
    console.log('❌ 验证码类型不支持:', type);
    return {
      success: false,
      message: '验证码类型不支持'
    }
  }

  console.log('📋 验证参数正确，开始查询验证码记录...');

  try {
    const codeResult = await db.collection('verify_codes')
      .where({
        phone: phone,
        code: code,
        type: type,
        used: false,
        expireTime: _.gte(new Date())
      })
      .get()

    if (codeResult.data.length === 0) {
      // 查询验证码是否存在但已过期
      const expiredCodeResult = await db.collection('verify_codes')
        .where({
          phone: phone,
          code: code,
          type: type,
          used: false
        })
        .get()

      if (expiredCodeResult.data.length > 0) {
        return {
          success: false,
          message: '验证码已过期，请重新获取'
        }
      }

      return {
        success: false,
        message: '验证码错误'
      }
    }

    // 标记验证码为已使用
    await db.collection('verify_codes').doc(codeResult.data[0]._id).update({
      data: {
        used: true,
        useTime: new Date()
      }
    })

    return {
      success: true,
      message: '验证码验证成功'
    }
  } catch (error) {
    console.error('验证验证码失败:', error)
    return {
      success: false,
      message: '验证验证码失败'
    }
  }
}

// 检查用户名是否可用
async function checkUsername(data) {
  const {
    username
  } = data

  if (!username) {
    return {
      success: false,
      message: '用户名不能为空'
    }
  }

  try {
    const result = await db.collection('users').where({
      username: username
    }).get()

    return {
      success: true,
      message: '检查完成',
      data: {
        available: result.data.length === 0
      }
    }
  } catch (error) {
    console.error('检查用户名错误:', error)
    return {
      success: false,
      message: '检查用户名失败'
    }
  }
}

// 检查手机号是否已注册
async function checkPhone(data) {
  const {
    phone
  } = data

  if (!phone) {
    return {
      success: false,
      message: '手机号不能为空'
    }
  }

  try {
    const result = await db.collection('users').where({
      phone: phone
    }).get()

    return {
      success: true,
      message: '检查完成',
      data: {
        exists: result.data.length > 0
      }
    }
  } catch (error) {
    console.error('检查手机号错误:', error)
    return {
      success: false,
      message: '检查手机号失败'
    }
  }
}